package com.tanhua.mongo.api;

import com.tanhua.api.VideoApi;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.PageResult;
import com.tanhua.mongo.util.IdWorker;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class VideoApiImpl implements VideoApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    //保存小视频数据
    @Override
    public String save(Video video) {
        //设置vid唯一标识
        video.setVid(idWorker.getNextId("video"));

        //保存
        mongoTemplate.save(video);

        //发那会小视频主键
        return video.getId().toHexString();
    }

    //根据vids 查询推荐视频
    @Override
    public List<Video> findByVids(List<Long> vids) {
        return mongoTemplate.find(Query.query(
                Criteria.where("vid").in(vids)
        ), Video.class);
    }

    //分页查询 按照发布时间倒序排序
    @Override
    public List<Video> findByPage(int page, Integer pagesize) {
        return mongoTemplate.find(
                new Query()
                        .skip((page - 1) * pagesize)
                        .limit(pagesize)
                        .with(Sort.by(Sort.Order.desc("created")))
                , Video.class);
    }

    //根据用户id 分页查询小视频数据
    @Override
    public PageResult findPageByUid(Long uid, Integer page, Integer pagesize) {
        //1 创建查询的条件  用户id
        Query query = Query.query(Criteria.where("userId").is(uid));

        //2 查询符合条件的总记录数
        long count = mongoTemplate.count(query, Video.class);

        //3 设置分页参数
        query.skip((page - 1) * pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));

        //4 执行分页查询
        List<Video> videoList = mongoTemplate.find(query, Video.class);

        //5 封装分页对象  返回结果
        return new PageResult(page, pagesize, (int) count, videoList);
    }

    @Override
    public boolean hasLike(String id, Long userId, CommentType like) {
        //创建查询条件
        Query query = Query.query(Criteria.where("id").is(new ObjectId(id))
                .and("userId").is(userId)
                .and("likeCount").is(like));

        //执行查询
        return mongoTemplate.exists(query, Comment.class);
    }

    @Override
    public Integer saves(Video video) {

        //1. 查询动态数据
        Video movement = mongoTemplate.findById(video.getVid(), Video.class);

        //2. 判断动态数据是否存在，如果不存在，就抛异常
        if (movement == null) {
            throw new RuntimeException("动态数据不存在，无法进行 评论、点赞、喜欢 互动操作！");
        }

        //-----------Movement动态数据操作：互动数据进行+1操作------------------
        //4. 设置修改的条件
        Query query = Query.query(Criteria.where("id").is(video.getId()));

        //5. 设置修改的数值 根据CommentType互动类型判断，对应的互动数量+1操作
        Update update = new Update();
        //根据评论类型，1-点赞，2-评论，3-喜欢  进行加一
        if (video.getLikeCount() == 1) {
            update.inc("likeCount", 1);
        }

        //设置修改参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true);//returnNew:设置是否返回修改后的值

        //6 使用 findAndModify 方法，实现修改并返回结果
        Movement modify = mongoTemplate.findAndModify(query, update, options, Movement.class);

        //7 返回互动的总数
        return modify.statisCount(video.getLikeCount());
    }
}
